package com.edgar.plugin.hooks;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.CompatibilityInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.edgar.plugin.PluginIntents;
import com.edgar.plugin.PluginManager;
import com.edgar.plugin.compat.ActivityThreadCompat;
import com.edgar.plugin.utils.FieldUtils;

/**
 * Created by Edgar on 2018/2/11.
 */
public class HandleCallbackHook extends Hook implements Handler.Callback{

    private static final String TAG = "HandleCallbackHook";
    public static final int LAUNCH_ACTIVITY = 100;
    private PluginManager mPluginManager;

    public HandleCallbackHook(Context context) {
        super(context);
        mPluginManager = PluginManager.getInstance();
    }

    @Override
    protected void onInstall(Context context) {
        super.onInstall(context);
        Handler handler = (Handler) FieldUtils.readField(ActivityThreadCompat.currentActivityThread(),"mH");
        FieldUtils.writeField(Handler.class,handler,"mCallback",this);
    }

    private static String getHookHandleMessage(Message msg){
        switch (msg.what){
            case LAUNCH_ACTIVITY:
                return "Hook LAUNCH_ACTIVITY";
            default:
                return "No Hook";
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        Log.d(TAG,">>> handling: "+getHookHandleMessage(msg));
        switch (msg.what){
            case LAUNCH_ACTIVITY:
                handleLaunchActivity(msg);
                break;
        }
        return false;
    }

    private void handleLaunchActivity(Message msg){
        Object activityClientRecord = msg.obj;
        Intent intent = (Intent) FieldUtils.readField(activityClientRecord,"intent");
        if (intent.hasExtra(PluginIntents.EXTRA_TARGET_INTENT)){
            Intent targetIntent = intent.getParcelableExtra(PluginIntents.EXTRA_TARGET_INTENT);
            FieldUtils.writeField(activityClientRecord,"intent",targetIntent);
            ActivityInfo activityInfo = mPluginManager.getActivityInfo(targetIntent.getComponent());
            FieldUtils.writeField(activityClientRecord,"activityInfo",activityInfo);
            CompatibilityInfo compatibilityInfo = (CompatibilityInfo) FieldUtils.readField(activityClientRecord,"compatInfo");
            mPluginManager.preparePlugin(mPluginManager.getPlugin(activityInfo.packageName),compatibilityInfo);
        }
    }
}